package com.vrv.drools.droolsdemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vrv.drools.droolsdemo.domain.DroolsRule;
import com.vrv.drools.droolsdemo.service.DroolsRuleService;
import com.vrv.drools.droolsdemo.mapper.DroolsRuleMapper;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.drools.core.impl.KnowledgeBaseImpl;
import org.kie.api.KieBase;
import org.kie.api.definition.KiePackage;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author Bang
 * @description 针对表【drools_rule】的数据库操作Service实现
 * @createDate 2023-11-01 10:42:11
 */
@Service
public class DroolsRuleServiceImpl extends ServiceImpl<DroolsRuleMapper, DroolsRule>
        implements DroolsRuleService {


    @Resource
    private KieContainer kieContainer;

    @Override
    public KieSession getSession() {
        KieSession kieSession = null;
        try {
            KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
            // 读取最新的规则配置
            List<DroolsRule> list = this.list();
            for (DroolsRule droolsRule : list) {
                builder.add(ResourceFactory.newByteArrayResource(droolsRule.getRule().getBytes(StandardCharsets.UTF_8)), ResourceType.DRL);
            }

            KnowledgeBaseImpl kieBase = (KnowledgeBaseImpl) kieContainer.getKieBase();
            Collection<KiePackage> packages = builder.getKnowledgePackages();
            // 将规则添加到规则库
            kieBase.addPackages(packages);

            kieSession = kieBase.newKieSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kieSession;
    }
}




